package com.linkoog.devtools.archive.filesystem.sevenzip;

import com.linkoog.devtools.archive.filesystem.ArchiveHandlerBase;
import com.linkoog.devtools.archive.filesystem.ArchiveFile;
import com.linkoog.devtools.archive.util.ArchiveUtils;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 */
public class SevenZipFile implements ArchiveFile {

    private final File _file;

    private Map<String, ArchiveEntry> entries;

    public SevenZipFile(File file) {
        _file = file;
    }

    @Override
    public Map<String, ArchiveHandlerBase.EntryInfo> createEntriesInfoMap() throws IOException {
        return ArchiveUtils.buildEntryMap(calculateEntries());
    }

    @Override
    public byte[] getEntryBytes(String relativePath) throws IOException {
        ArchiveEntry item = calculateEntries().get(relativePath);
        try (SevenZFile sevenZFile = new SevenZFile(_file, (char[]) null)){
            return ArchiveUtils.getEntryBytes(sevenZFile, item);
        }
    }

    @Override
    public ArchiveInputStream getInputStream() {
        return null;
    }

    @Override
    public void close() {
    }

    public Map<String, ArchiveEntry> calculateEntries() throws IOException {
        if (entries == null) {
            try (SevenZFile sevenZFile = new SevenZFile(_file, (char[]) null)){
                return entries = ArchiveUtils.calculateEntries(sevenZFile);
            }
        }
        else {
            return entries;
        }
    }

}